package com.kgc.mgj.config.api;

import com.kgc.mgj.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author ：jacketzc
 * @date ：Created in 2020/9/22 9:24
 * 登录验证拦截器，添加 @LoginRequired注解的请求需要用户登录才能访问
 */
@Slf4j
public class LoginRequiredComplete implements HandlerInterceptor {
    @Resource
    private RedisUtils redisUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
        if (null != loginRequired) {
            String token = request.getHeader("token");
            if (StringUtils.isEmpty(token)) {
                log.info("请求head中未携带token");
                throw new RuntimeException("login error,请求head中未携带token");
            }
            //从redis中取出用户信息，此处逻辑变更为查看 token是否存在于redis
            Object wxUserVoObj = redisUtils.get(token);
            if (ObjectUtils.isEmpty(wxUserVoObj)) {
                log.info("token已经过期");
                throw new RuntimeException("token error,token已经过期");
            }
            //将json格式的用户信息转换为对象
//            WxUserVo wxUserVo = JSONObject.parseObject((String)wxUserVoObj, WxUserVo.class);
//            request.setAttribute("WxUserVo", wxUserVo);
            request.setAttribute("openid",token);
            return true;
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
